<template>
  <el-row>
    <el-col :span="24">
      <el-card>
        <el-form :inline="true" class="demo-form-inline">
          <el-form-item>
            <el-button type="primary" @click="addDialogShow=true">添加</el-button>
          </el-form-item>
          <el-form-item style="float: right;">
            <el-input v-model="condition.name" placeholder="请输入要搜索的姓名" @input="selectByPage(1)"/>
          </el-form-item>
          <el-form-item style="float: right;">
            <el-select
                v-model="condition.status"
                clearable
                placeholder="请选择是否上架"
                :value-on-clear="null"
                style="width: 200px"
                @change="selectByPage(1)">
              <el-option label="上架" value="1"/>
              <el-option label="下架" value="0"/>
            </el-select>
          </el-form-item>
          <el-form-item style="float: right;">
            <el-cascader
                v-model="condition.categoryId"
                :options="allParent"
                :props="props"
                placeholder="请选择分类"
                :value-on-clear="null"
                clearable
                @change="selectByPage(1)"/>
          </el-form-item>
        </el-form>
        <el-table :data="pageInfo.list" border style="width:100%">
          <el-table-column prop="id" label="ID" width="50px"/>
          <el-table-column prop="name" label="名称"/>
          <el-table-column prop="dscp" label="描述"/>
          <el-table-column prop="price" label="售价"/>
          <el-table-column prop="markPrice" label="标价"/>
          <el-table-column prop="purchasePrice" label="进价"/>
          <el-table-column prop="color" label="颜色"/>
          <el-table-column prop="version" label="版本"/>
          <el-table-column prop="count" label="数量"/>
          <el-table-column label="是否推荐">
            <template #default="scope">
              <el-switch
                  v-model="scope.row.recom"
                  :active-value="1"
                  :inactive-value="0"
                  active-text="推荐"
                  inactive-text="不推荐"
                  inline-prompt
                  style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"
                  @change="chgRecom(scope.row.id, scope.row.recom,scope.row.picList)"
              />
            </template>
          </el-table-column>
          <el-table-column label="分类">
            <template #default="scope">
              <el-text class="mx-1" type="primary">{{ scope.row.category.name }}</el-text>
            </template>
          </el-table-column>
          <el-table-column prop="score" label="评分"/>
          <el-table-column label="是否上架">
            <template #default="scope">
              <el-switch
                  v-model="scope.row.status"
                  :active-value="0"
                  :inactive-value="1"
                  active-text="上架"
                  inactive-text="下架"
                  inline-prompt
                  style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"
                  @change="chgStatus(scope.row.id, scope.row.status,scope.row.picList)"
              />
            </template>
          </el-table-column>
          <el-table-column label="图片">
            <template #default="scope">
              <el-popover placement="right" trigger="hover" v-if="scope.row.picList.length > 0">
                <template #reference>
                  <el-image style="width: 20px; height: 20px"
                            :src="SERVER_ADDR+'/goods/pic/' + scope.row.picList[0].url"/>
                </template>
                <el-image v-for="(pic,index) in scope.row.picList" :key="index"
                          style="width:40px;height:40px;margin-right: 5px" :src="SERVER_ADDR+'/goods/pic/' + pic.url"/>
              </el-popover>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="150px">
            <template #default="scope">
              <el-button size="small" type="success" @click="showDetailDialog(scope.row)">详情</el-button>
              <el-button size="small" type="primary" @click="selectById(scope.row.id)">修改</el-button>
              <el-popconfirm title="确认删除?" confirm-button-text="确认" cancel-button-text="取消"
                             @confirm="deleteGoods(scope.row.id)">
                <template #reference>
                  <el-button size="small" type="danger">删除</el-button>
                </template>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
        <el-row class="row-bg" justify="center" style="margin-top:20px ;">
          <el-pagination background layout="prev, pager, next" :total="pageInfo.total"
                         :page-size="pageInfo.pageSize" @change="selectByPage"/>
        </el-row>
      </el-card>
    </el-col>
  </el-row>
  <!--添加分类对话框开始 -->
  <el-dialog v-model="addDialogShow" title="添加商品" width="600">
    <el-form>
      <el-form-item label="名称" label-width="25%">
        <el-cascader
            v-model="goodsAdd.categoryId"
            :options="allParent"
            :props="props"
            placeholder="请选择分类"
            :value-on-clear="null"
            clearable
        />
      </el-form-item>
      <el-form-item label="名称" label-width="25%">
        <el-input v-model="goodsAdd.name" placeholder="请输入名称" autocomplete="off" style="width: 300px"/>
      </el-form-item>
      <el-form-item label="描述" label-width="25%">
        <el-input v-model="goodsAdd.dscp" placeholder="请输入描述" autocomplete="off" style="width: 300px"/>
      </el-form-item>
      <el-form-item label="售价" label-width="25%">
        <el-input v-model="goodsAdd.price" placeholder="请输入售价" autocomplete="off" style="width: 300px"/>
      </el-form-item>
      <el-form-item label="标价" label-width="25%">
        <el-input v-model="goodsAdd.markPrice" placeholder="请输入标价" autocomplete="off" style="width: 300px"/>
      </el-form-item>
      <el-form-item label="进价" label-width="25%">
        <el-input v-model="goodsAdd.purchasePrice" placeholder="请输入售价" autocomplete="off" style="width: 300px"/>
      </el-form-item>
      <el-form-item label="颜色" label-width="25%">
        <el-input v-model="goodsAdd.color" placeholder="请输入颜色" autocomplete="off" style="width: 300px"/>
      </el-form-item>
      <el-form-item label="版本" label-width="25%">
        <el-input v-model="goodsAdd.version" placeholder="请输入版本" autocomplete="off" style="width: 300px"/>
      </el-form-item>
      <el-form-item label="数量" label-width="25%">
        <el-input v-model="goodsAdd.count" placeholder="请输入数量" autocomplete="off" style="width: 300px"/>
        <el-form-item label="是否推荐" label-width="25%">
          <el-radio-group v-model="goodsAdd.recom" style="width: 300px;">
            <el-radio label="不推荐" value="0" size="large"/>
            <el-radio label="推荐" value="1" size="large"/>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="是否上架" label-width="25%">
          <el-radio-group v-model="goodsAdd.status" style="width: 300px;">
            <el-radio label="下架" value="0" size="large"/>
            <el-radio label="上架" value="1" size="large"/>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="照片" label-width="20%">
          <el-upload v-model:file-list="goodsAdd.picList"
                     list-type="picture-card"
                     :action="SERVER_ADDR +'/category/upload'" name="pic"
                     :headers="headers"
                     :before-upload="beforePicUpload"
                     :on-success="picAddUploadSuccess"
          >
            <el-icon class="avatar-uploader-icon">
              <Plus/>
            </el-icon>
          </el-upload>
        </el-form-item>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="addDialogShow = false">取消</el-button>
        <el-button type="primary" @click="insert">确定</el-button>
      </div>
    </template>
  </el-dialog>
  <!--添加分类对话框结束-->
  <!--修改商品对话框开始 -->
  <el-dialog v-model="updateDialogShow" title="添加商品" width="600">
    <el-form>
      <el-form-item label="名称" label-width="25%">
        <el-cascader
            v-model="goodsUpdate.categoryId"
            :options="allParent"
            :props="props"
            placeholder="请选择分类"
            :value-on-clear="null"
            clearable
        />
      </el-form-item>
      <el-form-item label="名称" label-width="25%">
        <el-input v-model="goodsUpdate.name" placeholder="请输入名称" autocomplete="off" style="width: 300px"/>
      </el-form-item>
      <el-form-item label="ID" label-width="25%">
        <el-input v-model="goodsUpdate.id" placeholder="请输入名称" autocomplete="off" style="width: 300px"/>
      </el-form-item>
      <el-form-item label="描述" label-width="25%">
        <el-input v-model="goodsUpdate.dscp" placeholder="请输入描述" autocomplete="off" style="width: 300px"/>
      </el-form-item>
      <el-form-item label="售价" label-width="25%">
        <el-input v-model="goodsUpdate.price" placeholder="请输入售价" autocomplete="off" style="width: 300px"/>
      </el-form-item>
      <el-form-item label="标价" label-width="25%">
        <el-input v-model="goodsUpdate.markPrice" placeholder="请输入标价" autocomplete="off" style="width: 300px"/>
      </el-form-item>
      <el-form-item label="进价" label-width="25%">
        <el-input v-model="goodsUpdate.purchasePrice" placeholder="请输入售价" autocomplete="off" style="width: 300px"/>
      </el-form-item>
      <el-form-item label="颜色" label-width="25%">
        <el-input v-model="goodsUpdate.color" placeholder="请输入颜色" autocomplete="off" style="width: 300px"/>
      </el-form-item>
      <el-form-item label="版本" label-width="25%">
        <el-input v-model="goodsUpdate.version" placeholder="请输入版本" autocomplete="off" style="width: 300px"/>
      </el-form-item>
      <el-form-item label="数量" label-width="25%">
        <el-input v-model="goodsUpdate.count" placeholder="请输入数量" autocomplete="off" style="width: 300px"/>
        <el-form-item label="是否推荐" label-width="25%">
          <el-radio-group v-model="goodsUpdate.recom" style="width: 300px;">
            <el-radio label="不推荐" value="0" size="large"/>
            <el-radio label="推荐" value="1" size="large"/>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="是否上架" label-width="25%">
          <el-radio-group v-model="goodsUpdate.status" style="width: 300px;">
            <el-radio label="下架" value="0" size="large"/>
            <el-radio label="上架" value="1" size="large"/>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="照片" label-width="20%">
          <el-upload v-model:file-list="goodsUpdate.picList"
                     list-type="picture-card"
                     :action="SERVER_ADDR +'/category/upload'" name="pic"
                     :headers="headers"
                     :before-upload="beforePicUpload"
                     :on-success="picAddUploadSuccess"
          >
            <el-icon class="avatar-uploader-icon">
              <Plus/>
            </el-icon>
          </el-upload>
        </el-form-item>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="updateDialogShow = false">取消</el-button>
        <el-button type="primary" @click="update">确定</el-button>
      </div>
    </template>
  </el-dialog>
  <!--修改商品对话框结束 -->
  <!--商品详情对话框开始 -->
  <el-dialog v-model="detailDialogShow" title="商品详情" @onclose="detailDialogShow = false;">
    <div v-if="detailDialogShow" style="border: 1px solid #ccc">
      <Toolbar
          style="border-bottom: 1px solid #ccc"
          :editor="editorRef"
          :defaultConfig="toolbarConfig"
          :mode="mode"
      />
      <Editor
          style="height: 500px; overflow-y: hidden;"
          v-model="goodsUpdate.detail"
          :defaultConfig="editorConfig"
          :mode="mode"
          @onCreated="handleCreated"
      />
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="detailDialogShow = false">取消</el-button>
        <el-button type="primary" @click="updateDetail">确定</el-button>
      </div>
    </template>
  </el-dialog>
  <!--商品详情对话框结束 -->
</template>

<script setup>
import categoryApi from "@/api/CategoryApi.js";

import {ElMessage} from "element-plus";
import goodsApi from "@/api/goodsApi.js";
import '@wangeditor/editor/dist/css/style.css' // 引入 css
import {onBeforeUnmount, ref, shallowRef, onMounted, computed} from 'vue'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import {useTokenStore} from "@/stores/token.js";
const tokenStore = useTokenStore();
const headers = computed(() => {
  const token = tokenStore.tokenStr;
  return{
    token: token
  }
})

// 服务器路径
const SERVER_ADDR = ref(import.meta.env.VITE_SERVER_ADDR);
// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef()
const mode = ref('default')
// 内容 HTML

const toolbarConfig = {}
const editorConfig = {
  placeholder: '请输入内容...',
  MENU_CONF: {
    uploadImage:{
      server: `${SERVER_ADDR.value}/goods/upload`,
      fieldName:'pic',
      headers:{
        token:tokenStore.tokenStr
      },
      customInsert(resp,insertFn){
        let url =`${SERVER_ADDR.value}/goods/pic/${resp.data}`;
        insertFn(url)
      }
    }
  }
}

// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value
  if (editor == null) return
  editor.destroy()
})

const handleCreated = (editor) => {
  editorRef.value = editor // 记录 editor 实例，重要！
}
//搜索条件
const condition = ref({
  name: null,
  categoryId: null,
  status: null
});

//分页信息
const pageInfo = ref({
  pages: 0,
  pageSize: 0,
  pageNum: 0
});
//父分类
const allParent = ref([]);
//级联选择器配置选项
const props = {
  label: "name",
  value: "id",
  children: "childList",
  emitPath: false
}
//被添加商品的信息
const goodsAdd = ref({
  name: '',
  dscp: '',
  price: null,
  markPrice: null,
  purchasePrice: null,
  color: null,
  version: null,
  count: null,
  recom: null,
  categoryId: null,
  status: null,
  picList: []
});
//被修改商品的信息
const goodsUpdate = ref({
  id:0,
  name: '',
  dscp: '',
  detail:'',
  price: null,
  markPrice: null,
  purchasePrice: null,
  color: null,
  version: null,
  count: null,
  recom: null,
  categoryId: null,
  status: null,
  picList: []
});
//是否显示商品详情
const detailDialogShow = ref (false);
//是否显示添加的对话框
const addDialogShow = ref(false);
//是否显示修改的对话框
const updateDialogShow = ref(false);
//显示商品详情对话框
function showDetailDialog(goods){
  goodsUpdate.value.id = goods.id;
  goodsUpdate.value.detail = goods.detail;
  goodsUpdate.value.picList = goods.picList;
  detailDialogShow.value = true;
}
//修改商品详情
function  updateDetail(){
  goodsApi.update(goodsUpdate.value).then(resp => {
    if(resp.code == 10000){
      ElMessage.success(resp.msg);
      detailDialogShow.value = false;

      goodsUpdate.value ={
        name: '',
        dscp: '',
        detail:'',
        price: null,
        markPrice: null,
        purchasePrice: null,
        color: null,
        version: null,
        count: null,
        recom: null,
        categoryId: null,
        status: null,
        picList: []
      };
      selectByPage(pageInfo.value.pageNum)
    }else{
      ElMessage.error(resp.msg);
    }
  })
}

//修改
function update(){
  for (let i = 0; i<goodsUpdate.value.picList.length; i++) {
    goodsUpdate.value.picList[i].url = goodsUpdate.value.picList[i].realName;
  }
  goodsApi.update(goodsUpdate.value).then(resp => {
    if(resp.code == 10000){
      ElMessage.success(resp.msg);
      updateDialogShow.value = false;

      goodsUpdate.value ={
        name: '',
        dscp: '',
        detail:'',
        price: null,
        markPrice: null,
        purchasePrice: null,
        color: null,
        version: null,
        count: null,
        recom: null,
        categoryId: null,
        status: null,
        picList: []
      };
      selectByPage(pageInfo.value.pageNum)
    }else{
      ElMessage.error(resp.msg);
    }
  })
}
//根据id查询
function  selectById(id){
  goodsApi.selectById(id)
      .then(resp => {
        goodsUpdate.value = resp.data;
        //处理图片
        for (let i = 0; i<goodsUpdate.value.picList.length; i++){
          goodsUpdate.value.picList[i].realName = goodsUpdate.value.picList[i].url;
          goodsUpdate.value.picList[i].url =`${SERVER_ADDR.value}/goods/pic/${goodsUpdate.value.picList[i].url}`;

        }


        updateDialogShow.value = true;
      })
}
//上传图片前的回调
function beforePicUpload(rawFile) {
  if (rawFile.type !== 'image/jpeg') {
    ElMessage.error('图片仅支持jpg格式')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('图片不能超过2m')
    return false
  }
  return true
}

//是否推荐
function chgRecom(id, recom, picList) {
  const goods = {
    id,
    recom,
    picList
  }
  goodsApi.update(goods)
      .then(resp => {
        if (resp.code == 10000) {
          ElMessage.success(resp.msg)
          selectByPage(pageInfo.value.pageNum)
        } else {
          ElMessage.error(resp.msg)
        }
      })
}

//修改上架
function chgStatus(id, status, picList) {
  const goods = {
    id,
    status,
    picList
  }
  goodsApi.update(goods)
      .then(resp => {
        if (resp.code == 10000) {
          ElMessage.success(resp.msg)
          selectByPage(pageInfo.value.pageNum)
        } else {
          ElMessage.error(resp.msg)
        }
      })
}
//上传图片成功的回调
function picAddUploadSuccess(resp, uploadFile) {//resp - 服务器的响应 uploadFile - 1，当前上传的图片，2.和picList中对应的元素是绑定的
  if (resp.code == 10000) {
    ElMessage.success(resp.msg);
    uploadFile.url = `${SERVER_ADDR.value}/goods/pic/${resp.data}`;
    uploadFile.realName = resp.data;
  } else {
    ElMessage.error(resp.msg);
  }
}

function deleteGoods(id) {
  goodsApi.delete(id)
      .then(resp => {
        if (resp.code == 10000) {
          ElMessage.success(resp.msg);
          //查询第一页
          selectByPage(1);
        } else {
          ElMessage(resp.msg)
        }
      })
}

//分页查询
function selectByPage(pageNum) {
  goodsApi.selectByPage(condition.value, pageNum, 15)
      .then(resp => {
        pageInfo.value = resp.data;
      })
}

//获取所有父分类
function selectAllParent() {
  categoryApi.selectAllParent()
      .then(resp => {
        allParent.value = resp.data;
      })
}

function insert() {
  //处理图片 realName -> url
  for (let i = 0; i < goodsAdd.value.picList.length; i++) {
    goodsAdd.value.picList[i].url = goodsAdd.value.picList[i].realName;
  }
  goodsApi.insert(goodsAdd.value)
      .then(resp => {
        if (resp.code == 10000) {
          ElMessage.success(resp.msg);
          addDialogShow.value = false;
          goodsAdd.value = {
            name: '',
            dscp: '',
            price: null,
            markPrice: null,
            purchasePrice: null,
            color: null,
            version: null,
            count: null,
            recom: null,
            categoryId: null,
            status: null,
            picList: []
          };
          selectByPage(1);
        } else {
          ElMessage.error(resp.msg);
        }
      });
}

selectAllParent();
selectByPage(1);
</script>

<style scoped>

</style>